package com.dushuren.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dushuren.project.common.BaseResponse;
import com.dushuren.project.common.ErrorCode;
import com.dushuren.project.common.ResultUtils;
import com.dushuren.project.constant.CommonConstant;
import com.dushuren.project.exception.BusinessException;
import com.dushuren.project.mapper.*;
import com.dushuren.project.model.dto.*;
import com.dushuren.project.model.entity.*;
import com.dushuren.project.model.vo.TeamCureExamineVo;
import com.dushuren.project.model.vo.TeamVo;
import com.dushuren.project.model.vo.UserTeamVo;
import com.dushuren.project.model.vo.UserVo;
import com.dushuren.project.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import static com.dushuren.project.constant.TeamConstant.*;


/**
 * 队伍接口
 * @author dushuren
 */
@RestController
@RequestMapping("/team")
@CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
public class TeamController {

  @Resource
  TeamService teamService;

  @Resource
  TeamCureExamineService teamCureExamineService;

  @Resource
  TeamMapper teamMapper;

  @Resource
  TeamCureExamineMapper teamCureExamineMapper;

  @Resource
  UserService userService;

  @Resource
  UserTeamMapper userTeamMapper;

  @Resource
  UserTeamService userTeamService;
  
  @Resource
  UserMapper userMapper;

  @Resource
  TeamApplyService teamApplyService;

  @Resource
  SuggestNotWordsSearchService suggestNotWordsSearchService;

  @Resource
  TeamApplyMapper teamApplyMapper;

  @Resource
  RecordWordsSearchService recordWordsSearchService;

  // IO 型线程池
  private final ExecutorService ioExecutorService = new ThreadPoolExecutor(4, 20, 10, TimeUnit.MINUTES,
    new ArrayBlockingQueue<>(10000));



  /**
   * 创建team
   */
  @PostMapping("/add")
  public BaseResponse<Integer> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
    if (teamAddRequest == null) {
      throw new BusinessException(ErrorCode.NULL_ERROR);
    }
    Boolean result = teamService.addTeam(teamAddRequest,request);
    if (Boolean.FALSE.equals(result)) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }
    return ResultUtils.success(TEAM_STATE_IN);
  }

  /**
   * 管理员 删除队伍
   */
  @PostMapping("/delete")
  public BaseResponse<Boolean> deleteTeam(@RequestBody TeamDeleteRequest teamDeleteRequest, HttpServletRequest request){
    Long teamId = teamDeleteRequest.getTeamId();
    if (teamId <= 0) {
      throw new BusinessException(ErrorCode.NULL_ERROR);
    }
    // 校验是否为管理员
    userService.isAdministrators(request);
    QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("id");
    queryWrapper.eq("id", teamId);
    boolean remove = teamService.remove(queryWrapper);
//    Long id = teamDeleteRequest.getId();
//    if (id == null || id < 0) {
//      throw new BusinessException(ErrorCode.PARAMS_ERROR);
//    }
//
//    Boolean result = teamService.deleteTeam(id,request);
    return ResultUtils.success(remove);
  }


  /**
   * 更新队伍基础信息
   */
  @PostMapping("/update/base")
  public BaseResponse<Boolean> updateBaseTeam(@RequestBody TeamUpdateBaseRequest teamUpdateBaseRequest, HttpServletRequest request){

    if (teamUpdateBaseRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    if (StringUtils.isAnyBlank(teamUpdateBaseRequest.getTeamType(),teamUpdateBaseRequest.getTeamTechnologyType())){
      throw new BusinessException(ErrorCode.NULL_ERROR);
    }
    if (teamUpdateBaseRequest.getMaxNum() != null && (TEAM_MAX_NUM < teamUpdateBaseRequest.getMaxNum() || TEAM_MIN_NUM > teamUpdateBaseRequest.getMaxNum())){
      throw new BusinessException(ErrorCode.NULL_ERROR);
    }
    Boolean result =  teamService.updateBaseTeam(teamUpdateBaseRequest, request);

    return ResultUtils.success(result);
  }

  /**
   * 更新公开的队伍信息
   */
  @PostMapping("/update/cure")
  public BaseResponse<Long> updateCureTeam(@RequestBody TeamUpdateCureRequest updateCureRequest, HttpServletRequest request) {

    if (updateCureRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    if (updateCureRequest.getTeamId() == null && updateCureRequest.getUserId() < 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    if (updateCureRequest.getTeamName() == null && updateCureRequest.getTeamDescription() == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    Long result = teamService.updateCureTeam(updateCureRequest, request);
    return ResultUtils.success(result);
  }

  /**
   * 管理员 查询 所有队伍
   */
//  @GetMapping("/list/query")
//  public BaseResponse<List<TeamVo>> listQueryTeam(TeamListQueryRequest teamListQueryRequest, HttpServletRequest request) {
//    // 判断是否为管理员
//    userService.isAdministrators(request);
//    Integer teamApplyState = teamListQueryRequest.getTeamApplyState();
//    if (teamApplyState == null) {
//      teamApplyState = 1; // 默认查询所有通过审核的队伍
//    }
//    // 直接返回所有 isAnyBlank 但里面出现为空的时候 isAllEmpty 全部为空就返回 true 否则相反
//    if (StringUtils.isAllEmpty(teamListQueryRequest.getTeamDescription(),teamListQueryRequest.getTeamName(),teamListQueryRequest.getTeamType()
//      ,teamListQueryRequest.getTeamDescription()
//    ) && (teamListQueryRequest.getMaxNum() == null && teamListQueryRequest.getId() == null && teamListQueryRequest.getUserId() == null) )
//    {
//      QueryWrapper<Team> queryWrapperTeam = new QueryWrapper<>();
//      queryWrapperTeam.select("id", "teamName", "teamDescription",
//        "maxNum", "teamType", "teamTechnologyType", "userId", "createTime","teamApplyState");
//      queryWrapperTeam.eq("teamApplyState" ,teamApplyState);
//      List<TeamVo> teamVos = teamMapper.selectList(queryWrapperTeam).stream().map(
//        team -> {
//          TeamVo teamVo = new TeamVo();
//          BeanUtils.copyProperties(team, teamVo);
//          return teamVo;
//        }
//      ).collect(Collectors.toList());
//      return ResultUtils.success(teamVos);
//    }
//    List<TeamVo> resultQueryTeam = teamService.listQueryTeam(teamListQueryRequest, teamApplyState);
//
//    if (resultQueryTeam == null) {
//      return ResultUtils.success(new ArrayList<TeamVo>());
//    }
//    return ResultUtils.success(resultQueryTeam);
//  }


  /**
   * 管理员 分页查询（默认查询 state 为1 的队伍）所有队伍
   * @param teamListQueryRequest
   * @param request
   * @return
   */
  @GetMapping("/list/query")
  public BaseResponse<Page<TeamVo>> listQueryTeam(TeamListQueryRequest teamListQueryRequest, HttpServletRequest request) {
    // 判断是否为管理员
    userService.isAdministrators(request);
    Integer teamApplyState = teamListQueryRequest.getTeamApplyState();
    if (teamApplyState == null) {
      teamApplyState = 1; // 默认查询所有通过审核的队伍
    }
    // 直接返回所有 isAnyBlank 但里面出现为空的时候 isAllEmpty 全部为空就返回 true 否则相反
    if (StringUtils.isAllEmpty(teamListQueryRequest.getTeamDescription(),teamListQueryRequest.getTeamName(),teamListQueryRequest.getTeamType()
      ,teamListQueryRequest.getTeamDescription()
    ) && (teamListQueryRequest.getMaxNum() == null && teamListQueryRequest.getId() == null && teamListQueryRequest.getUserId() == null) )
    {
      QueryWrapper<Team> queryWrapperTeam = new QueryWrapper<>();
      queryWrapperTeam.select("id", "teamName", "teamDescription",
        "maxNum", "teamType", "teamTechnologyType", "userId", "createTime","teamApplyState", "teamAvatarUrl");
      queryWrapperTeam.eq("teamApplyState" ,teamApplyState);
      long current = teamListQueryRequest.getCurrent();
      long size  = teamListQueryRequest.getPageSize();
      Page<Team> teamPage = teamService.page(new Page<>(current, size), queryWrapperTeam);
      Map<Long, List<TeamVo>> teamIdListMap = teamPage.getRecords().stream().map(team -> {
        TeamVo teamVo = new TeamVo();
        BeanUtils.copyProperties(team, teamVo);
        teamVo.setMinNum(team.getMaxNum() - teamService.teamWantingAmount(team.getId()));
        teamVo.setApply(2);
        return teamVo;
      }).collect(Collectors.groupingBy(TeamVo::getId));
      Page<TeamVo> teamVoPage = new Page<>(teamPage.getCurrent(), teamPage.getSize(), teamPage.getTotal());
      teamVoPage.setRecords(teamIdListMap.values().stream()
        .flatMap(Collection::stream)
        .collect(Collectors.toList()));
      return ResultUtils.success(teamVoPage);
    }
    Page<TeamVo> teamVoPage = teamService.listPageQueryTeam(teamListQueryRequest, teamApplyState);
    return ResultUtils.success(teamVoPage);
  }



  /**
   * 管理员 修改 队伍信息
   */
  @PostMapping("/update/query")
  public BaseResponse<Long> updateQueryTeam(@RequestBody TeamUpdateQueryTeam updateQueryTeam, HttpServletRequest request) {
    // 检验是否为管理员
    userService.isAdministrators(request);

    Long id = updateQueryTeam.getId();
    String teamName = updateQueryTeam.getTeamName();
    String teamDescription = updateQueryTeam.getTeamDescription();
    Integer maxNum = updateQueryTeam.getMaxNum();
    String teamType = updateQueryTeam.getTeamType();
    String teamTechnologyType = updateQueryTeam.getTeamTechnologyType();
    Long userId = updateQueryTeam.getUserId();
    Integer teamApplyState = updateQueryTeam.getTeamApplyState();
    QueryWrapper<Team> queryWrapperTeam = new QueryWrapper<>();
    queryWrapperTeam.select("id", "maxNum", "teamType", "teamTechnologyType","teamStatus","teamType","teamTechnologyType","userId","teamApplyState","teamApplyMessage");
    queryWrapperTeam.eq("id",id);
    Team team = teamMapper.selectOne(queryWrapperTeam);
    if (team.getId() <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    // 查询当前队伍的信息
    UpdateWrapper<Team> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id",id);

    if (!teamName.equals(team.getTeamName())) {
      updateWrapper.set("teamName",teamName);
    }
    if (!teamDescription.equals(team.getTeamDescription())) {
      updateWrapper.set("teamDescription",teamDescription);
    }
    if (!maxNum.equals(team.getMaxNum())) {
      updateWrapper.set("maxNum",maxNum);
    }
    if (!teamType.equals(team.getTeamType())) {
      updateWrapper.set("teamType",teamType);
    }
    if (!teamTechnologyType.equals(team.getTeamTechnologyType())) {
      updateWrapper.set("teamTechnologyType",teamTechnologyType);
    }
    if (!userId.equals(team.getUserId())) {
      updateWrapper.set("userId",userId);
    }
    if (!teamApplyState.equals(team.getTeamApplyState())) {
      updateWrapper.set("teamApplyState",teamApplyState);
    }
    int update = teamMapper.update(null, updateWrapper);
    if (update != 1) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    return ResultUtils.success(0L);
  }

  /**
   * 分页 查询所有审核通过的队伍
   */
  @GetMapping("/list/open")
  public BaseResponse<Page<TeamVo>> listOpenTeam(TeamListQueryRequest teamListQueryRequest, HttpServletRequest request) {
    User user = userService.getLoginUser(request);
    if (teamListQueryRequest == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    Team teamQuery = new Team();
    BeanUtils.copyProperties(teamListQueryRequest, teamQuery);
    long current = teamListQueryRequest.getCurrent();
    long size  = teamListQueryRequest.getPageSize();
    String sortField = teamListQueryRequest.getSortField();
    String sortOrder = teamListQueryRequest.getSortOrder();
    String teamDescription = teamQuery.getTeamDescription();
    String teamTechnologyType = teamQuery.getTeamTechnologyType();

    // 使用 并发编程进行编写 》 对用户输入的数据进行监听
    CompletableFuture.runAsync(() -> {
      if (StringUtils.isNotBlank(teamDescription) && teamDescription.length() < 8) {
        // 查询数据是否含有“不推荐创” Words
        boolean isDeregulationResult = suggestNotWordsSearchService.wordsIsDeregulation(teamDescription);
        if (isDeregulationResult) {
          recordWordsSearchService.QueryIsRecordWords(user.getId(), teamDescription);
        }
      }
    }, ioExecutorService);

    // description 支持模糊查询
    teamQuery.setTeamDescription(null);
    // 限制爬虫
    if (size > 50) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    QueryWrapper<Team> queryWrapper = new QueryWrapper<>(teamQuery);
    queryWrapper.like(StringUtils.isNotBlank(teamDescription), "teamDescription", teamDescription).or().like(StringUtils.isNotBlank(teamDescription), "teamName", teamDescription);

    queryWrapper.like(StringUtils.isNotBlank(teamTechnologyType),"teamTechnologyType", teamTechnologyType);
    queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
          sortOrder.equals(CommonConstant.SORT_ORDER_ASC),sortField);
    Page<Team> teamPage = teamService.page(new Page<>(current, size), queryWrapper);
    Map<Long, List<TeamVo>> teamIdListMap = teamPage.getRecords().stream().map(team -> {
      TeamVo teamVo = new TeamVo();
      BeanUtils.copyProperties(team, teamVo);
      teamVo.setMinNum(team.getMaxNum() - teamService.teamWantingAmount(team.getId()));
      teamVo.setApply(2);
      return teamVo;
    }).collect(Collectors.groupingBy(TeamVo::getId));
    // 已登入，获取加入状态 获取当前用户的申请队伍
    try {
      Set<Long> longs = teamIdListMap.keySet();
      if (!longs.isEmpty()) {
        QueryWrapper<TeamApply> teamApplyQueryWrapper = new QueryWrapper<>();
        teamApplyQueryWrapper.eq("userId", user.getId());
        teamApplyQueryWrapper.in("teamId", longs);
        Long count = teamApplyMapper.selectCount(teamApplyQueryWrapper);
        if (count != 0) {
          List<TeamApply> teamApplyList = teamApplyService.list(teamApplyQueryWrapper);
          teamApplyList.forEach( teamApply ->
            teamIdListMap.get(teamApply.getTeamId()).get(0).setApply(teamApply.getApplyReviewStatus()));
        }
      }

    } catch (Exception e){
      // 未登入的 不处理
    }
    Page<TeamVo> teamVoPage = new Page<>(teamPage.getCurrent(), teamPage.getSize(), teamPage.getTotal());
    teamVoPage.setRecords(teamIdListMap.values().stream()
      .flatMap(Collection::stream)
      .collect(Collectors.toList()));
    return ResultUtils.success(teamVoPage);
  }


  /**
   * 通过队伍 teamId 查询队伍信息
   */
  @GetMapping("/get/query")
  public BaseResponse<TeamVo> getQueryTeam(int teamId, HttpServletRequest request) {
    userService.isAdministrators(request);
    if (teamId < 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    QueryWrapper<Team> queryWrapperTeam = new QueryWrapper<>();
    queryWrapperTeam.select("id", "teamName", "teamDescription",
      "maxNum", "teamType", "teamTechnologyType", "userId");
    queryWrapperTeam.eq("teamApplyState" ,1);
    queryWrapperTeam.eq("id", teamId);
    TeamVo teamVo = new TeamVo();
    Team team = teamMapper.selectOne(queryWrapperTeam);
    if (team != null) {
      BeanUtils.copyProperties(team, teamVo);
    }
    return ResultUtils.success(teamVo);
  }

  /**
   * 查看当前用户加入的队伍
   */
  @GetMapping("/list/get/team")
  public BaseResponse<List<TeamVo>> listGetTeam(HttpServletRequest request){
    User loginUser = userService.getLoginUser(request);
    // 查询自己加入的队伍
    QueryWrapper<UserTeam> queryWrapperUserTeam = new QueryWrapper<>();
    queryWrapperUserTeam.select("teamId");
    queryWrapperUserTeam.eq("userId", loginUser.getId());
    QueryWrapper<Team> queryWrapperTeam = new QueryWrapper<>();
    queryWrapperTeam.select("id", "teamName", "teamDescription",
      "maxNum", "teamType", "teamTechnologyType", "userId", "createTime", "teamAvatarUrl");

    List<Long> collect = userTeamMapper.selectList(queryWrapperUserTeam).stream().map(UserTeam::getTeamId).collect(Collectors.toList());

    queryWrapperTeam.eq("teamApplyState", TEAM_STATE_ADOPT);
    queryWrapperTeam.in("id", collect);
    List<Team> teams = new ArrayList<>();
    try {
      teams = teamMapper.selectList(queryWrapperTeam);
    }catch (Exception e) {
      // 没值不做处理
    }
    List<TeamVo> collect1 = new ArrayList<>();
    if (teams != null) {
      collect1 = teams.stream().map(team -> {
        TeamVo teamVo = new TeamVo();
        teamVo.setMinNum(team.getMaxNum() - teamService.teamWantingAmount(team.getId()));
        BeanUtils.copyProperties(team, teamVo);
        teamVo.setCureStatus(teamCureExamineService.cureApplyTeam(teamVo.getId())); // 存在申请的则就为1  不存在这就为0
        return teamVo;
      }).collect(Collectors.toList());
    }
    return ResultUtils.success(collect1);
  }
  /**
   * 个人 查看当前用户创建的队伍
   */
  @GetMapping("/list/get/query/team")
  public BaseResponse<List<TeamVo>> listGetQueryTeam(HttpServletRequest request){
    User loginUser = userService.getLoginUser(request);
    QueryWrapper<Team> queryWrapperTeam = new QueryWrapper<>();
    queryWrapperTeam.select("id", "teamName", "teamDescription",
      "maxNum", "teamType", "teamTechnologyType", "userId", "createTime","teamAvatarUrl");
    queryWrapperTeam.eq("userId", loginUser.getId());
    queryWrapperTeam.eq("teamApplyState", TEAM_STATE_ADOPT);

    List<TeamVo> collect1 = teamMapper.selectList(queryWrapperTeam).stream().map(team -> {
      TeamVo teamVo = new TeamVo();
      teamVo.setMinNum(team.getMaxNum() - teamService.teamWantingAmount(team.getId()));
      BeanUtils.copyProperties(team, teamVo);
      teamVo.setCureStatus(teamCureExamineService.cureApplyTeam(teamVo.getId())); // 存在申请的则就为1  不存在这就为0
      return teamVo;
    }).collect(Collectors.toList());
    return ResultUtils.success(collect1);
  }

  /**
   * 个人 查询当前队伍的信息
   */
  @GetMapping("/list/member/team")
  public BaseResponse<TeamVo> listMemberTeam(Long id, HttpServletRequest request) {
    userService.getLoginUser(request);
    QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("id", "teamName", "teamDescription",
      "maxNum", "teamType", "teamTechnologyType", "userId", "createTime", "teamAvatarUrl");
    queryWrapper.eq("id", id);
    TeamVo teamVo = new TeamVo();
    Team team = teamMapper.selectOne(queryWrapper);
    BeanUtils.copyProperties(team, teamVo);
    teamVo.setMember(teamService.allMember(id));
    return ResultUtils.success(teamVo);
  }

  /**
   *  创建队伍的审核通过
   */
  @PostMapping("/apply/Adopt")
  public BaseResponse<Long> applyAdoptTeam(@RequestBody TeamApplyAdoptRequest applyAdoptRequest, HttpServletRequest request) {
    userService.isAdministrators(request);
    Long teamId = applyAdoptRequest.getTeamId();
    teamService.checkApplyState(teamId);
    UpdateWrapper<Team> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id", teamId);
    updateWrapper.set("teamApplyState", 1);
    teamMapper.update(null,updateWrapper);
    return ResultUtils.success(teamId);
  }


  /**
   *  创建队伍的审核不通过
   */
  @PostMapping("/apply/noAdopt")
  public BaseResponse<Long> applyNoAdoptTeam(@RequestBody TeamApplyNoAdoptRequest noAdoptRequest, HttpServletRequest request) {
    userService.isAdministrators(request);
    Long teamId = noAdoptRequest.getTeamId();
    teamService.checkApplyState(teamId);

    UpdateWrapper<Team> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id", teamId);
    updateWrapper.set("teamApplyState", 2);
    String teamApplyMessage = noAdoptRequest.getTeamApplyMessage();
    if (StringUtils.isNotBlank(teamApplyMessage)) {
      updateWrapper.set("teamApplyMessage", teamApplyMessage);
    }
    teamMapper.update(null,updateWrapper);
    return ResultUtils.success(teamId);
  }

  /**
   * 查询队伍自定义内容更改审核 默认查询为通过的队伍
   */
  @GetMapping("/list/examine")
  public BaseResponse<Page<TeamCureExamineVo>> listUpdateCureApplyTeam(TeamUpdateCureExamineRequest updateCureExamineRequest, HttpServletRequest request){
    // 使用mybatis-plus 的分页查询时，需要注意 需要有分页的页数和页码 count size
    userService.isAdministrators(request);
    Integer examineState = updateCureExamineRequest.getExamineState();
    if (examineState == null) {
      examineState = 0; // 默认查询未通过的队伍
    }
    Page<TeamCureExamine> page;
    // 直接返回所有 isAnyBlank 但里面出现为空的时候 isAllEmpty 全部为空就返回 true 否则相反
    if (StringUtils.isAllEmpty(updateCureExamineRequest.getTeamCureCategory(),updateCureExamineRequest.getTeamInformation())
      && (updateCureExamineRequest.getTeamId() == null && updateCureExamineRequest.getId() == null && updateCureExamineRequest.getUserId() == null))
    {
      QueryWrapper<TeamCureExamine> queryWrapperTeam = new QueryWrapper<>();
      queryWrapperTeam.select("id", "userId", "teamId",
        "teamCureCategory", "teamInformation","createTime", "examineState", "examineInformation");
      queryWrapperTeam.eq("examineState" ,examineState);
      long pageSize = updateCureExamineRequest.getPageSize();
      long current = updateCureExamineRequest.getCurrent();
      page = teamCureExamineService.page(new Page<>(current, pageSize), queryWrapperTeam);
    } else {
      page = teamCureExamineService.listQueryTeam(updateCureExamineRequest, examineState);
      if (page == null) {
        return ResultUtils.success(new Page<>());
      }
    }
    Page<TeamCureExamineVo> pageVo = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
    pageVo.setRecords(page.getRecords().stream().map( teamCureExamine -> {
      TeamCureExamineVo teamCureExamineVo = new TeamCureExamineVo();
      BeanUtils.copyProperties(teamCureExamine, teamCureExamineVo);
      return teamCureExamineVo;
    }).collect(Collectors.toList()));
    return ResultUtils.success(pageVo);
  }


  /**
   * 队伍 更新审核通过
   */
  @PostMapping("/update/apply")
  @Transactional(rollbackFor = Exception.class)
  public BaseResponse<Long> examineUpdateApplyTeam(@RequestBody TeamUpdateApplyRequest updateApplyRequest, HttpServletRequest request){
    userService.isAdministrators(request);
    Long id = updateApplyRequest.getId();
    TeamCureExamine teamCureExamine = teamCureExamineService.checkApplyState(id);
    UpdateWrapper<TeamCureExamine> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id", id);
    updateWrapper.set("examineState", 1);
    teamCureExamineMapper.update(null,updateWrapper);
    // 修改队伍信息
    UpdateWrapper<Team> updateWrapperTeam = new UpdateWrapper<>();
    updateWrapperTeam.eq("id", teamCureExamine.getTeamId());
    updateWrapperTeam.eq("userId", teamCureExamine.getUserId());
    updateWrapperTeam.set(teamCureExamine.getTeamCureCategory(), teamCureExamine.getTeamInformation());
    teamMapper.update(null, updateWrapperTeam);
    return ResultUtils.success(id);
  }


  /**
   * 队伍 更新审核不通过
   */
  @PostMapping("/update/noApply")
  public BaseResponse<Long> examineUpdateNoApplyTeam(@RequestBody TeamUpdateNoApplyRequest updateNoApplyRequest, HttpServletRequest request){
    userService.isAdministrators(request);
    Long id = updateNoApplyRequest.getId();
    teamCureExamineService.checkApplyState(id);
    UpdateWrapper<TeamCureExamine> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("id", id);
    updateWrapper.set("examineState", 2);
    String examineInformation = updateNoApplyRequest.getExamineInformation();
    if (StringUtils.isNotBlank(examineInformation)) {
      updateWrapper.set("examineInformation", examineInformation);
    }
    teamCureExamineMapper.update(null,updateWrapper);
    return ResultUtils.success(id);
  }


  /**
   * 退出队伍
   */
  @PostMapping("/bowout")
  @Transactional(rollbackFor = Exception.class)
  public BaseResponse<Long> bowOutTeam(@RequestBody TeamBowOutRequest teamBowOutRequest, HttpServletRequest request) {
    UserVo userVO = userService.getIsServletRequest(request);
    Long teamId = teamBowOutRequest.getTeamId();
    Long userId = teamBowOutRequest.getUserId();
    if (!userVO.getId().equals(userId)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("id");
    queryWrapper.eq("teamId", teamId);
    queryWrapper.eq("userId", userId);
    Long count = userTeamMapper.selectCount(queryWrapper);
    if (count != 1) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    //1. 校验是否为本队队长，如果为本队队长，需要当前队伍人数 = 1 时才能进行退出。
    QueryWrapper<Team> queryWrapperTeam = new QueryWrapper<>();
    queryWrapperTeam.select("id");
    queryWrapperTeam.eq("id",teamId);
    queryWrapperTeam.eq("userId",userId);
    Long count1 = teamMapper.selectCount(queryWrapperTeam);
    if (count1 == 1) {
      // 校验当前队伍人数是否 == 1
      Long aLong = userTeamService.QueryTeamNum(teamId);
      if (aLong > 1) {
        throw new BusinessException(ErrorCode.PARAMS_ERROR, "队长不能直接退出");
      }
      // 解散队伍
      boolean remove = teamService.remove(queryWrapperTeam);
      if (Boolean.FALSE.equals(remove)) {
        throw new BusinessException(ErrorCode.SYSTEM_ERROR);
      }
    }
    boolean remove = userTeamService.remove(queryWrapper);
    if (Boolean.FALSE.equals(remove)) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }
    return ResultUtils.success(0L);
  }

  /**
   * 队伍 踢出成员
   */
  @PostMapping("/kick")
  @Transactional(rollbackFor = Exception.class)
  public BaseResponse<Long> kickTeam(@RequestBody TeamKickRequest teamKickRequest, HttpServletRequest request) {
    UserVo userVO = userService.getIsServletRequest(request);
    Long captainId = teamKickRequest.getCaptainId();
    Long teamId = teamKickRequest.getTeamId();
    Long userId = teamKickRequest.getUserId();
    if (!userVO.getId().equals(captainId)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("id");
    queryWrapper.eq("id", teamId);
    queryWrapper.eq("userId", captainId);
    if (teamMapper.selectCount(queryWrapper) != 1) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    QueryWrapper<UserTeam> queryWrapperUserTeam = new QueryWrapper<>();
    queryWrapperUserTeam.select("id");
    queryWrapperUserTeam.eq("teamId",teamId);
    queryWrapperUserTeam.eq("userId", userId);
    if (userTeamMapper.selectCount(queryWrapperUserTeam) != 1){
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    boolean remove = userTeamService.remove(queryWrapperUserTeam);
    Boolean aBoolean = teamApplyService.applyDeleteTeam(teamId, userId);
    if (Boolean.FALSE.equals(aBoolean)) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }
    if (Boolean.FALSE.equals(remove)) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }
    return ResultUtils.success(0L);
  }

  /**
   *  查看当前队伍成员信息
   */
  @GetMapping("/Query/member")
  public BaseResponse<List<UserTeamVo>> queryMemberTeam(TeamQueryMemberRequest queryMemberRequest, HttpServletRequest request) {
    UserVo userVO = userService.getIsServletRequest(request);
    Long teamId = queryMemberRequest.getTeamId();
    Long userId = queryMemberRequest.getUserId();
    if (userVO.getId().equals(userId)) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    Long aLong = userTeamService.QueryTeamNum(teamId, userId);
    if (aLong != 1) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("id", "userId", "teamId", "joinTeam");
    queryWrapper.eq("teamId", teamId);

    List<UserTeamVo> resultResponse = userTeamMapper.selectList(queryWrapper).stream().map(userTeam -> {
      UserTeamVo userTeamVo = new UserTeamVo();
      BeanUtils.copyProperties(userTeam, userTeamVo);
      // 获取到个人信息
      QueryWrapper<User> queryWrapperUser = new QueryWrapper<>();
      queryWrapperUser.select("userAccount", "userName", "avatarUrl", "gender", "userProfile", "phone", "email", "tags");
      queryWrapperUser.eq("id", userTeam.getUserId());
      UserVo userVo = new UserVo();
      BeanUtils.copyProperties(userMapper.selectOne(queryWrapperUser), userVo);
      userTeamVo.setUserVo(userVo);
      return userTeamVo;
    }).collect(Collectors.toList());
    return ResultUtils.success(resultResponse);
  }

  /**
   * 转让队长 （现实基础操作）
   */
  @PostMapping("/let/captain")
  @Transactional(rollbackFor = Exception.class)
  public BaseResponse<Long> captainLetTeam(@RequestBody TeamCaptainLetRequest captainLetRequest, HttpServletRequest request) {
    UserVo userVO = userService.getIsServletRequest(request);
    Long teamId = captainLetRequest.getTeamId();
    Long userId = captainLetRequest.getUserId();
    if (userId <= 0 || teamId <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    Long id = userVO.getId();
    if (Objects.equals(userId, id)) {
      throw new BusinessException(ErrorCode.NULL_ERROR, "不能转让给自己");
    }
    // 校验当前是否存在于这个队伍
    UserTeamVo idTeamExist = userTeamService.isIdTeamExist(teamId, userId);

    // 现在开始队长转让 > 修改当前队伍的队长即可
    UpdateWrapper<Team> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("userId", id);
    updateWrapper.eq("id", teamId);
    updateWrapper.set("userId",idTeamExist.getUserId());
    teamMapper.update(null,updateWrapper);

    return ResultUtils.success(0L);
  }

  /**
   * 查询个人申请创建的队伍列表
   * @param request 登入态
   * @return
   */
  @GetMapping("/list/apply")
  public BaseResponse<List<TeamVo>> listApplyTeam(HttpServletRequest request){
    UserVo isServletRequest = userService.getIsServletRequest(request);
    if (isServletRequest.getId() <= 0) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("id", "teamName", "teamDescription",
      "maxNum", "teamType", "teamTechnologyType", "userId", "createTime");
    queryWrapper.eq("teamApplyState", TEAM_STATE_IN);
    queryWrapper.eq("userId", isServletRequest.getId());
    List<TeamVo> collect = teamMapper.selectList(queryWrapper).stream().map(team -> {
        TeamVo teamVo = new TeamVo();
        BeanUtils.copyProperties(team, teamVo);
        return teamVo;
      }
    ).collect(Collectors.toList());
    return ResultUtils.success(collect);
  }


  /**
   * 个人 删除还在申请中的队伍
   */
  @PostMapping("/delete/apply")
  public BaseResponse<Long> deleteApplyTeam(@RequestBody TeamDeleteApplyRequest deleteApplyRequest, HttpServletRequest request){
    UserVo isServletRequest = userService.getIsServletRequest(request);
    Long teamId = deleteApplyRequest.getTeamId();
    if (teamId <= 0 ) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    // 校验这个申请队伍是否存在，存在则删除
    QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("id");
    queryWrapper.eq("teamApplyState", TEAM_STATE_IN);
    queryWrapper.eq("userId", isServletRequest.getId());
    queryWrapper.eq("id",teamId);
    Long count = teamMapper.selectCount(queryWrapper);
    if (count != 1) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    boolean remove = teamService.remove(queryWrapper);
    if (Boolean.FALSE.equals(remove)) {
      throw new BusinessException(ErrorCode.SYSTEM_ERROR);
    }
    return ResultUtils.success(0L);
  }
}
